package homework;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.HashMap;
import java.util.Random;

public class java07_RandomCallName5 {
	public static void main(String[] args) throws IOException {
		/* 
		 * 作业5：
		 * 名单里十个学生，初始每个人被抽中的概率相同，每被抽中一次概率降低一半
		 * 
		 */
		FileReader fr = new FileReader("nameList.txt");
		BufferedReader br = new BufferedReader(fr);
		String line = null;
		HashMap<String,Double> map = new HashMap<String, Double>();
		HashMap<Integer,String> findName = new HashMap<Integer, String>();
		
		//录入按值寻人名和按人名寻概率两张HashMap
		int order = 0;
		while((line = br.readLine())!=null&&line.length()>0) {
			String[] info = line.split("-");
			map.put(info[0],Double.parseDouble(info[1]));
			findName.put(order, info[0]);
			order++;
		}
		
		//抽取总次数
		int totalTimes = 1;
		Random r =new Random();
		for(int i=0;i<totalTimes;i++) {
			double totalRate = 0;
			double [] rates = new double[11];
			rates[0] = 0;
			for(int l=0,j=1;l<10;l++,j++) {
				String name = findName.get(l);
				totalRate += map.get(name);
				rates[j] = totalRate;
			}
			
			//查看随机数生成与各人被抽到的范围
			
//			System.out.println(totalRate);
//			System.out.println(Arrays.toString(rates));
			double num = r.nextDouble()*totalRate;
//			System.out.println(num);
			for(int l=0;l<10;l++) {
				if(num>rates[l]&&num<rates[l+1]) {
					String key = findName.get(l);
					double rate = map.get(key)/2;
					map.put(key,rate);
					System.out.println(key + " 当前概率：" + rate);
//					System.out.println(l);
				}
			}
			//写入文件保存
			FileWriter fw = new FileWriter("nameList.txt");
			BufferedWriter bw = new BufferedWriter(fw);
			for(int l=0;l<map.size();l++) {
				String key = findName.get(l);
				double value = map.get(key);
				bw.write(key+"-"+value);
				bw.newLine();
			}
			bw.close();
		}
	}
}
